from django.shortcuts import render, redirect, HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from django.urls import reverse  
from django.db.models import F, Q, Count, IntegerField, ExpressionWrapper, CharField, Func
from django.db.models.functions import Replace, Cast
from django.views.decorators.csrf import csrf_exempt
from .models import NoinfoAnime, NoinfoMovie, NoinfoWatchrecord, NoinfoTeleplay, NoinfoNovel
import re, json
from django.core import serializers

# 查询观看记录
def search_watch(request):
    if request.method == 'GET':
        query = request.GET.get('name', '')  # 获取查询参数，默认为空字符串  
        view_status = request.GET.get('view_status')
        type = request.GET.get('type')  
        results = NoinfoWatchrecord.objects.filter(name__icontains=query).order_by('-id')  # 执行模糊查询，这里假设您要查询的字段是theme 
        if view_status == 'ing':
            results = results.filter(Q(date_watch_end__isnull=True))
        else:
            pass
        if type == 'anime':
            results = results.filter(code__icontains='anime')
        elif type == 'movie':
            results = results.filter(code__icontains='movie')
        elif type == 'teleplay':
            results = results.filter(code__icontains='teleplay')
        elif type == 'novel':
            results = results.filter(code__icontains='novel')
        else:
            pass
        for result in results:
            if result.date_watch_start is not None:
                if result.date_watch_end is None or len(str(result.date_watch_end)) == 0:
                    result.duration = '在看'
                else:
                    result.duration = (result.date_watch_end - result.date_watch_start).days
                    if result.duration == 0:
                        result.duration = '当天'
                        
        return render(request, 'search_watch.html', {'results': results})  # 将查询结果传递给模板进行呈现